<script setup>
import { getArticleByIdAPI } from '@/api'
import errorLogger from '@/utils/errorLogger'
import {
  computed,
  onBeforeUnmount,
  onMounted,
  ref,
  shallowRef,
  watch,
} from 'vue'
import { useRoute } from 'vue-router'
import { Editor } from '@wangeditor/editor-for-vue'

const route = useRoute()
const article = ref(null)
const isLoading = ref(false)
const articleContent = ref('')
const editorRef = shallowRef(null)
const editorConfig = Object.freeze({
  placeholder: '内容加载中…',
})

const formatDate = (value) => {
  if (!value) return '未知时间'
  try {
    return new Date(value).toLocaleString()
  } catch (error) {
    errorLogger(error)
    return value
  }
}

const fetchArticle = async (id) => {
  if (!id) return
  isLoading.value = true
  try {
    const result = await getArticleByIdAPI(id)
    article.value = result.data
    articleContent.value = result.data?.content || ''
  } catch (error) {
    errorLogger(error)
  } finally {
    isLoading.value = false
  }
}

onMounted(() => {
  fetchArticle(route.params.id)
})

watch(
  () => route.params.id,
  (newId, oldId) => {
    if (newId && newId !== oldId) {
      fetchArticle(newId)
    }
  },
)

const metaInfo = computed(() => ({
  category:
    typeof article.value?.category === 'object'
      ? article.value?.category?.name
      : article.value?.category,
  tags: Array.isArray(article.value?.tags)
    ? article.value.tags.map((tag) =>
        typeof tag === 'object' ? tag.name : tag,
      )
    : [],
  createdAt: formatDate(article.value?.createdAt),
  updatedAt: formatDate(article.value?.updatedAt),
}))

const coverImage = computed(() => {
  return (
    article.value?.coverImage ||
    'https://images.unsplash.com/photo-1524995997946-a1c2e315a42f'
  )
})

const handleEditorCreated = (editor) => {
  editorRef.value = editor
  editor.disable?.()
}

onBeforeUnmount(() => {
  if (!editorRef.value) return
  editorRef.value.destroy()
  editorRef.value = null
})
</script>

<template>
  <div class="container article-preview">
    <div v-if="isLoading" class="article-loading">
      <el-skeleton animated :rows="6" />
    </div>

    <div v-else-if="article" class="article-content">
      <header class="article-header">
        <div class="article-meta">
          <span class="category-tag">{{ metaInfo.category || '未分类' }}</span>
          <time>{{ metaInfo.createdAt }}</time>
        </div>
        <h1>{{ article.title }}</h1>
        <p class="summary" v-if="article.summary">{{ article.summary }}</p>
        <div class="tags" v-if="metaInfo.tags.length">
          <el-tag
            v-for="tag in metaInfo.tags"
            :key="tag"
            effect="light"
            type="info">
            {{ tag }}
          </el-tag>
        </div>
      </header>

      <figure class="cover-image">
        <img :src="coverImage" :alt="article.title" />
      </figure>

      <section class="article-body">
        <Editor
          v-model="articleContent"
          :defaultConfig="editorConfig"
          mode="default"
          class="article-viewer"
          @onCreated="handleEditorCreated" />
      </section>

      <footer class="article-footer">
        <span>最后更新：{{ metaInfo.updatedAt }}</span>
      </footer>
    </div>

    <el-empty v-else description="未找到文章" />
  </div>
</template>

<style lang="scss" scoped>
.article-preview {
  padding: 48px 0;
  max-width: 960px;

  .article-loading {
    background: var(--color-surface);
    border-radius: 16px;
    padding: 32px;
    box-shadow: 0 12px 40px rgba(15, 23, 42, 0.08);
  }

  .article-content {
    background: var(--color-surface);
    color: var(--color-text);
    border-radius: 18px;
    padding: 40px 48px;
    box-shadow: 0 20px 60px rgba(15, 23, 42, 0.1);
    backdrop-filter: blur(12px);
  }

  .article-header {
    text-align: center;
    margin-bottom: 36px;

    h1 {
      font-size: 2.6rem;
      font-weight: 700;
      line-height: 1.25;
      margin-bottom: 12px;
      color: var(--color-text);
    }

    .summary {
      color: var(--color-gray-1);
      font-size: 1.05rem;
      max-width: 680px;
      margin: 0 auto;
      line-height: 1.7;
    }
  }

  .article-meta {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 16px;
    margin-bottom: 18px;
    color: var(--color-gray-2);
    font-size: 0.95rem;

    .category-tag {
      background: var(--color-primary);
      color: var(--color-light);
      padding: 6px 14px;
      border-radius: 999px;
      font-weight: 600;
      letter-spacing: 0.5px;
    }
  }

  .tags {
    display: flex;
    gap: 10px;
    justify-content: center;
    flex-wrap: wrap;
    margin-top: 18px;
  }

  .cover-image {
    margin: 30px 0;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 18px 45px rgba(15, 23, 42, 0.2);

    img {
      width: 100%;
      height: 420px;
      object-fit: cover;
      display: block;
    }
  }

  .article-body {
    .article-viewer {
      border: none;
      background: transparent;

      :deep(.w-e-scroll) {
        min-height: 200px;
      }

      :deep(.w-e-text-container) {
        font-size: 1.06rem;
        line-height: 1.9;
        color: var(--color-text);
        letter-spacing: 0.1px;
        background: transparent;
        padding: 0;

        h2 {
          font-size: 1.8rem;
          margin-top: 36px;
          margin-bottom: 16px;
          color: var(--color-text);
        }

        h3 {
          font-size: 1.4rem;
          margin-top: 28px;
          margin-bottom: 14px;
          color: var(--color-text);
        }

        p {
          margin-bottom: 18px;
          color: var(--color-text);
        }

        img {
          max-width: 100%;
          border-radius: 12px;
          margin: 20px 0;
          box-shadow: 0 12px 30px rgba(15, 23, 42, 0.12);
        }

        blockquote {
          border-left: 4px solid var(--color-primary);
          padding-left: 18px;
          color: var(--color-gray-1);
          font-style: italic;
          background: var(--color-light);
          border-radius: 0 10px 10px 0;
        }
      }
    }
  }

  .article-footer {
    margin-top: 48px;
    text-align: right;
    color: var(--color-gray-2);
    font-size: 0.9rem;
  }
}

@media (max-width: 768px) {
  .article-preview {
    padding: 24px 0;

    .article-content {
      padding: 28px 24px;
    }

    .cover-image img {
      height: 240px;
    }

    .article-header h1 {
      font-size: 2rem;
    }
  }
}
</style>
